import json
import logging

from typing import Any
from flask.views import MethodView
from flask import jsonify, Response, request, render_template

from ..exceptions import ParseError


log = logging.getLogger(__name__)


def to_json(
    request_data: bytes,
    debug: bool = False
) -> Any:
    if debug:
        log.debug(request_data)
    try:
        return json.loads(request_data)
    except ValueError as e:
        log.error('invalid json: %s', request_data)
        log.exception(e)
        raise ParseError(data={'message': 'Invalid JSON: {0!r}'.format(request_data)})
        # raise ValueError('Invalid JSON')


class APIView(MethodView):
    def __init__(
        self,
        jsonrpc,
        debug: bool = False
    ):
        self.jsonrpc = jsonrpc
        self.debug = debug
        if debug:
            log.debug('Connect JSON-RPC to Flask complete')

    def get(self):
        pagedata = {'title': 'API Browse'}
        body = render_template('api_browse.html', pagedata=pagedata)
        return body

    def post(self):
        json_data = to_json(request.data)
        result = self.jsonrpc(json_data)
        if debug:
            log.debug(result)
        return jsonify(result)
